'use strict';

const ulid = require('../public/ulid');

const Service = require('egg').Service;

class RoleService extends Service {
  async list(params) {
    return await this.ctx.modelmysql.RoleInfo.findAndCountAll({
      where: { tid: params.tid },
      order: [[ 'createdAt', 'ASC' ]],
      offset: parseInt((params.page - 1) * params.limit),
      limit: parseInt(params.limit),
    });
  }
  async listAll(tid) {
    return await this.ctx.modelmysql.RoleInfo.findAll({
      where: { tid },
      order: [[ 'createdAt', 'ASC' ]],
    });
  }
  async create(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.modelmysql.RoleInfo.create({
        id: ulid.ulid(),
        name: params.roleName,
        RoleCode: params.roleCode,
        tid: params.tid,
      });
      result.msg = 'create successful';
      return result;
    } catch (error) {
      result.msg = 'create fail';
      return result;
    }
  }
  async delete(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.modelmysql.RoleInfo.destroy({ where: { id: params.id } });
      result.msg = 'delete successful';
      return result;
    } catch (error) {
      result.msg = 'delete fail';
      return result;
    }
  }
  async edit(params) {
    const result = {
      msg: '',
    };
    try {
      await this.ctx.model.Role.update({
        name: params.name,
        pages: params.pages,
      }, {
        where: { id: params.id },
      });
      result.msg = 'edit successful';
      return result;
    } catch (error) {
      result.msg = 'edit successful';
      return result;
    }
  }
  async single(params) {
    const result = await this.ctx.modelmysql.RoleInfo.findOne({ where: { id: params.id } });
    const arr = JSON.parse(result.menus);
    const menus = [];
    if (!arr) {
      return menus;
    }
    arr.forEach(element => {
      menus.push(element);
    });
    return menus;

  }
  async roleInfoUpdateMenus(params) {
    const arr = JSON.stringify(params.menus);
    const result = {
      msg: '',
    };
    try {
      await this.ctx.modelmysql.RoleInfo.update({ menus: arr }, { where: { id: params.id } });
      result.msg = 'menus management successful';
      return result;
    } catch (error) {
      result.msg = 'menus management fail' + error;
      return result;
    }
  }
  async roleuser(params) {
    const Op = this.ctx.modelmysql.Sequelize.Op;
    const result = await this.ctx.modelmysql.RoleInfo.findAll({ where: {
      id: {
        [Op.in]: params,
      },
    } });
    let menus = '';
    result.forEach(element => {
      menus += JSON.parse(element.menus).join(',') + ',';
    });
    const menuarr = menus.split(',');
    menuarr.pop();
    const s = new Set(menuarr);
    const a = Array.from(s);
    const urlResult = {};
    // 查询出当前角色所对应的所有的可见模块
    const moduleList = await this.ctx.modelmysql.Menu.findAll({
      where: {
        id: {
          [Op.in]: a,
        },
        type: 1,
      },
    });
    // 查询出当前角色所对应的所有的可见菜单
    const menuList = await this.ctx.modelmysql.Menu.findAll({
      where: {
        id: {
          [Op.in]: a,
        },
        type: 0,
      },
    });

    // 查询出当前角色所对应的所有可见按钮
    const btnList = await this.ctx.modelmysql.Menu.findAll({
      where: {
        id: {
          [Op.in]: a,
        },
        type: 2,
      },
    });
    const obj = {};
    btnList.forEach(item => {
      const parentId = item.module_id;
      if (!obj.hasOwnProperty(parentId)) {
        obj[parentId] = {
          children: [],
        };
      }
      obj[parentId].children.push({
        type: item.type,
        name: item.name,
        sort: item.sort,
        url: item.url,
      });
    });

    menuList.forEach(item => {
      if (obj.hasOwnProperty(item.id)) {
        obj[item.id].type = item.type;
        obj[item.id].name = item.name;
        obj[item.id].sort = item.sort;
        obj[item.id].url = item.url;
        if (!urlResult.hasOwnProperty(item.module_id)) {
          urlResult[item.module_id] = {
            children: [],
          };
        }
        urlResult[item.module_id].children.push(obj[item.id]);
      } else {
        obj[item.id] = {
          type: item.type,
          name: item.name,
          sort: item.sort,
          url: item.url,
          children: [],
        };
        if (!urlResult.hasOwnProperty(item.module_id)) {
          urlResult[item.module_id] = {
            children: [],
          };
        }
        urlResult[item.module_id].children.push(obj[item.id]);
      }
    });
    moduleList.forEach(item => {
      if (urlResult.hasOwnProperty(item.id)) {
        urlResult[item.id].type = item.type;
        urlResult[item.id].name = item.name;
        urlResult[item.id].sort = item.sort;
        urlResult[item.id].url = item.url;
      }
    });
    return urlResult;
  }
}

module.exports = RoleService;
